"""
键盘按键代码测试工具 - 用于调试按键识别问题
"""
from pynput import keyboard
import time

# 当前按下的键集合
current_keys = set()

def on_press(key):
    """按键按下处理函数"""
    current_keys.add(key)
    
    if isinstance(key, keyboard.Key):
        print(f"按下特殊键: {key}, 属性名: {key.name if hasattr(key, 'name') else '无名称'}")
    elif isinstance(key, keyboard.KeyCode):
        print(f"按下按键码: {key}, 字符: {key.char if hasattr(key, 'char') else '无字符'}")
    
    print(f"当前按下的所有键: {current_keys}")
    
    # 检查是否按下了Esc键，用于退出程序
    if key == keyboard.Key.esc:
        # 停止监听
        return False

def on_release(key):
    """按键释放处理函数"""
    if key in current_keys:
        current_keys.remove(key)
        
    print(f"释放键: {key}, 剩余键: {current_keys}")

def test_key_detection():
    """测试按键检测"""
    print("===== 键盘按键检测测试 =====")
    print("请按下任何键，观察输出。按ESC退出测试。")
    print("常见的修饰键值:")
    print("- Ctrl键通常为: keyboard.Key.ctrl, keyboard.Key.ctrl_l, keyboard.Key.ctrl_r")
    print("- Shift键通常为: keyboard.Key.shift, keyboard.Key.shift_l, keyboard.Key.shift_r")
    print("- Alt键通常为: keyboard.Key.alt, keyboard.Key.alt_l, keyboard.Key.alt_r")
    print()
    print("测试组合键时，请同时按下多个键并观察它们的值")
    print("测试热键 'Ctrl+Shift+Space' 请同时按住这三个键")
    print("============================")
    
    # 启动按键监听
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        try:
            listener.join()
        except Exception as e:
            print(f"监听时出错: {e}")

if __name__ == "__main__":
    test_key_detection()
